package vashion.azeroth.core.service.tran.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vashion.azeroth.cart.obj.CartItemDO;
import vashion.azeroth.contant.carts.CartsConstant;
import vashion.azeroth.contant.carts.CartsErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.pojo.PropertyValueDO;
import vashion.azeroth.core.manager.personal.tran.PersonalCartsManager;
import vashion.azeroth.core.personal.tran.pojo.PersonalCarts;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.item.ItemReadService;
import vashion.azeroth.core.service.tran.PersonalCartsService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PersonalCartsServiceImpl implements PersonalCartsService {

	private final static Logger log = LoggerFactory
			.getLogger(PersonalCartsServiceImpl.class);

	@Autowired
	ItemReadService itemReadService;

	@Autowired
	PersonalCartsManager personalCartManager;

	@Override
	public ApiResult<Boolean> addCarts(PersonalCarts personalCarts) {

		// ----------------------00.参数校验-------------------------------------

		if (personalCarts == null || personalCarts.getItemId() == null
				|| personalCarts.getQuantity() == null
				|| personalCarts.getQuantity() <= 0) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		try {
			// ----------------------01.查询商品是否存在-------------------------------------
			Long itemId = personalCarts.getItemId();

			ApiResult<ItemDO> result = itemReadService.getItemDetail(itemId,
					true);

			if (!result.isSuccess()) {

				log.error("查询商品失败，商品ID: " + itemId + ",errorCode = "
						+ result.getErrorCode() + " errorMsg:"
						+ result.getErrorMsg());

				return ApiResult.newErrorResult(
						CartsErrorEnum.ITEM_NOT_EXIST.getErrorCode(),
						"商品查询错误 ：itemId = " + itemId + " 错误原因："
								+ result.getErrorMsg());

			}

			ItemDO itemDO = result.getData();

			if (itemDO == null
					|| itemDO.getStatus() != ItemStatusEnum.ORIGIN_STATUS
							.getStatus()) {

				return ApiResult.newErrorResult(
						CartsErrorEnum.ITEM_NOT_EXIST.getErrorCode(),
						CartsErrorEnum.ITEM_NOT_EXIST.getErrorMessage());

			}

			// ----------------------02.查询商品SKU是否存在-------------------------------------

			List<ItemSkuDO> itemSkuList = itemDO.getItemSkuDOList();

			if (itemSkuList == null && personalCarts.getSkuId() == null) {

				// 默认不存在这种情况
				log.error("商品SKU为空！ itemId:" + itemId);
				return ApiResult.newErrorResult(
						CartsErrorEnum.ITEM_NOT_EXIST.getErrorCode(),
						CartsErrorEnum.ITEM_NOT_EXIST.getErrorMessage()
								+ "商品SKU为空");

			}

			if (personalCarts.getSkuId() != null && itemSkuList.size() == 0) {
				// SKU不存在
				return ApiResult.newErrorResult(
						CartsErrorEnum.SKU_NOT_EXIST.getErrorCode(),
						CartsErrorEnum.SKU_NOT_EXIST.getErrorMessage());

			}

			if (personalCarts.getSkuId() == null && itemSkuList.size() != 0) {
				// 未选择SKU
				return ApiResult.newErrorResult(
						CartsErrorEnum.SKU_NOT_SELECT.getErrorCode(),
						CartsErrorEnum.SKU_NOT_SELECT.getErrorMessage());

			}

			// 判断SKU是否属于该商品

			Long skuId = personalCarts.getSkuId();

			if (!checkSku(skuId, itemSkuList)) {

				return ApiResult.newErrorResult(
						CartsErrorEnum.SKU_NOT_EXIST.getErrorCode(),
						CartsErrorEnum.SKU_NOT_EXIST.getErrorMessage());
			}

			// ----------------------03.查询商品数量是否已经达到50个-------------------------------------

			PersonalCarts newPersonalCarts = new PersonalCarts();

			newPersonalCarts.setMemberId(personalCarts.getMemberId());

			newPersonalCarts.setItemId(personalCarts.getItemId());

			newPersonalCarts.setSkuId(personalCarts.getSkuId());

			newPersonalCarts
					.setState(CartsConstant.CartsStatusConstant.ON_SALE);

			List<PersonalCarts> personalCartsList = personalCartManager
					.find(newPersonalCarts);

			if (!personalCartsList.isEmpty() && personalCartsList.size() > 1) {

				log.error("数据出错，查询结果数据库返回为：" + personalCartsList.size());

				// 数据错误
				return ApiResult.newErrorResult(
						CartsErrorEnum.DATE_ERROR.getErrorCode(),
						CartsErrorEnum.DATE_ERROR.getErrorMessage());
			}

			// 如果已存在，更新数据库

			if (!personalCartsList.isEmpty() && personalCartsList.size() == 1) {

				/**
				 * @TODO 判断商品是否超出库存
				 * 
				 * 
				 * */

				Integer old = personalCartsList.get(0).getQuantity();
				personalCartsList.get(0).setQuantity(
						old + personalCarts.getQuantity());

				Boolean isExcced = isExceedStock(personalCartsList.get(0),
						itemSkuList);

				if (isExcced) {
					return ApiResult.newErrorResult(
							CartsErrorEnum.INVENTORY_EXCEED.getErrorCode(),
							CartsErrorEnum.INVENTORY_EXCEED.getErrorMessage());

				}

				PersonalCarts p = personalCartsList.get(0);

				// 目前只有更新数量和时间
				// 商品数量已在上面校验的时候累加上

				p.setTimeEdit(new Date());

				p.setPublishFileId(personalCarts.getPublishFileId());

				int num = personalCartManager.update(p);

				return ApiResult.newSuccessResult(true);

			}

			// ----------------------04.查询商品数量是否已经超过50件-------------------------------------
			// 查询买家购物车商品数量

			PersonalCarts cntPersonalCarts = new PersonalCarts();

			cntPersonalCarts.setMemberId(personalCarts.getMemberId());

			cntPersonalCarts
					.setState(CartsConstant.CartsStatusConstant.ON_SALE);

			int cartCnt = personalCartManager.findCnt(cntPersonalCarts);

			if (cartCnt >= CartsConstant.MAX_CART_CNT) {

				return ApiResult.newErrorResult(
						CartsErrorEnum.CART_MAX_50.getErrorCode(),
						CartsErrorEnum.CART_MAX_50.getErrorMessage());
			}

			// ----------------------05.写入DB，存在更新，不存在写入-------------------------------------

			Boolean isExcced = isExceedStock(personalCarts, itemSkuList);

			if (isExcced) {
				return ApiResult.newErrorResult(
						CartsErrorEnum.INVENTORY_EXCEED.getErrorCode(),
						CartsErrorEnum.INVENTORY_EXCEED.getErrorMessage());

			}

			Date d = new Date();
			newPersonalCarts.setTimeAdd(d);
			newPersonalCarts.setTimeEdit(d);

			newPersonalCarts.setQuantity(personalCarts.getQuantity());
			newPersonalCarts.setPublishFileId(personalCarts.getPublishFileId());

			personalCartManager.save(newPersonalCarts);

			return ApiResult.newSuccessResult(true);

		} catch (Exception e) {

			log.error("出错啦" + e.getMessage());

			return ApiResult.newErrorResult(
					CartsErrorEnum.SYSTEM_ERROR.getErrorCode(),
					CartsErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
	}

	@Override
	public ApiResult<List<CartItemDO>> removeOneItemFromCarts(Long memberId,
			Long cartId) {

		if (memberId == null || cartId == null) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		try {

			Integer status = CartsConstant.CartsStatusConstant.BUYER_DELETE;

			ApiResult<Boolean> result = removeItemCommon(memberId, cartId,
					status);

			return myCarts(memberId);

		} catch (Exception e) {

			log.error("删除购物车商品出错啦，" + e.getMessage());

			return ApiResult.newErrorResult(
					CartsErrorEnum.SYSTEM_ERROR.getErrorCode(),
					CartsErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
	}

	@Override
	public ApiResult<List<CartItemDO>> removeMuliItemFromCarts(
			Long memberId, List<Long> cartIdList) {

		if (memberId == null || cartIdList == null || cartIdList.size() == 0) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		for (Long cartId : cartIdList) {

			// 循环删除

			removeOneItemFromCarts(memberId, cartId);

		}

		return myCarts(memberId);

	}

	@Override
	public ApiResult<List<CartItemDO>> myCarts(Long memberId) {

		if (memberId == null || memberId <= 0) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());

		}

		PersonalCarts personalCarts = new PersonalCarts();

		personalCarts.setMemberId(memberId);

		personalCarts.setState(CartsConstant.CartsStatusConstant.ON_SALE);

		List<PersonalCarts> personalCartsList = personalCartManager
				.find(personalCarts);

		List<CartItemDO> cic = convert2CartsItemContext(personalCartsList);

		return ApiResult.newSuccessResult(cic, personalCartsList.size());
	}

	@Override
	public ApiResult<Boolean> operateCartItem(PersonalCarts personalCarts) {

		// 目前只支持商品数量修改

		Integer quality = personalCarts.getQuantity();

		Long cartId = personalCarts.getCartId();

		Long memberId = personalCarts.getMemberId();

		if (quality == null || cartId == null || memberId == null) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());

		}

		PersonalCarts newPersonalCarts = new PersonalCarts();

		newPersonalCarts.setCartId(cartId);

		newPersonalCarts.setMemberId(memberId);

		List<PersonalCarts> personalCartsList = personalCartManager
				.find(newPersonalCarts);

		if (personalCartsList == null || personalCartsList.size() != 1) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.DATA_NOT_EXIST.getErrorCode(),
					CartsErrorEnum.DATA_NOT_EXIST.getErrorMessage());

		}

		// 检查库存

		ApiResult<ItemDO> api = itemReadService.getItemDetail(personalCartsList
				.get(0).getItemId(), true);

		if (!api.isSuccess()) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.DATA_NOT_EXIST.getErrorCode(),
					CartsErrorEnum.DATA_NOT_EXIST.getErrorMessage());

		}

		Boolean isExcced = isExceedStock(personalCartsList.get(0), api
				.getData().getItemSkuDOList());

		if (isExcced) {
			return ApiResult.newErrorResult(
					CartsErrorEnum.INVENTORY_EXCEED.getErrorCode(),
					CartsErrorEnum.INVENTORY_EXCEED.getErrorMessage());

		}
		newPersonalCarts.setQuantity(quality);

		newPersonalCarts.setTimeEdit(new Date());

		int i = personalCartManager.update(newPersonalCarts);

		if (!(i == 1)) {

			log.error("修改数量为 " + i + " 个,查询一下原因：memberId=" + memberId
					+ ",cartId:" + cartId);
		}

		return ApiResult.newSuccessResult(true);
	}

	@Override
	public ApiResult<Boolean> dealAfterCreatOrder(Long memberId,
			List<Long> cartIdList) {

		if (memberId == null || cartIdList == null || cartIdList.size() == 0) {

			return ApiResult.newErrorResult(
					CartsErrorEnum.PARAMETER_ERROR.getErrorCode(),
					CartsErrorEnum.PARAMETER_ERROR.getErrorMessage());
		}

		Integer status = CartsConstant.CartsStatusConstant.DELETE_AFTER_CREAT_ORDER;

		// 目前直接调用批量删除接口
		for (Long cartId : cartIdList) {

			removeItemCommon(memberId, cartId, status);

		}

		return ApiResult.newSuccessResult(true);
	}

	private boolean checkSku(Long skuId, List<ItemSkuDO> itemSkuList) {

		boolean b = false;

		if (itemSkuList == null || itemSkuList.size() == 0) {
			return b;
		}

		for (ItemSkuDO sku : itemSkuList) {

			Long aucSkuId = sku.getId();

			if (skuId.equals(aucSkuId)) {

				return true;
			}
		}

		return b;
	}

	private List<CartItemDO> convert2CartsItemContext(
			List<PersonalCarts> personalCartsList) {

		List<CartItemDO> cartItemList = new ArrayList<CartItemDO>();

		if (personalCartsList.isEmpty() || personalCartsList.size() == 0) {

			return cartItemList;
		}

		for (PersonalCarts p : personalCartsList) {

			Long itemId = p.getItemId();

			ApiResult<ItemDO> result = itemReadService.getItemDetail(itemId,
					true);

			if (result == null || !result.isSuccess()
					|| result.getData() == null) {
				continue;
			}

			CartItemDO cid = convertObj(result.getData(), p);

			if (cid.getStatus() == ItemStatusEnum.ORIGIN_STATUS.getStatus()) {
				cartItemList.add(cid);
			} else {

				// #TODO 暂时在购物车不展示这类商品，什么都不做

				// offSaleCartItemList.add(cid);
			}

		}

		return cartItemList;
	}

	private CartItemDO convertObj(ItemDO item, PersonalCarts p) {

		CartItemDO cid = new CartItemDO();

		cid.setCartId(p.getCartId());

		cid.setMemberId(p.getMemberId());

		cid.setItemId(p.getItemId());

		cid.setUserId(item.getUserId());

		cid.setSkuId(p.getSkuId());

		cid.setQuantity(p.getQuantity());

		cid.setStatus(item.getStatus());

		cid.setTitle(item.getTitle());

		cid.setPic(item.getPic());

		cid.setPublishFileId(p.getPublishFileId());

		List<ItemSkuDO> itemSkuList = item.getItemSkuDOList();

		for (ItemSkuDO sku : itemSkuList) {

			if (p.getSkuId().equals(sku.getId())) {

				cid.setPrice(sku.getItemPrice());

//				cid.setPromotionPrice(item.getPromotionPrice());

				cid.setVipPrice(item.getVipPrice());

				cid.setSkuName(convertSkuName(sku));

				cid.setStock(sku.getStock());
			}

		}
		return cid;

	}

	// 是否超出库存
	private boolean isExceedStock(PersonalCarts personalCarts,
			List<ItemSkuDO> itemSkuList) {

		boolean b = false;

		Long skuId = personalCarts.getSkuId();

		Integer quality = personalCarts.getQuantity();

		for (ItemSkuDO sku : itemSkuList) {

			if (skuId.equals(sku.getId())) {

				b = (quality > sku.getStock()) ? true : false;

				return b;
			}
		}

		return b;
	}

	private ApiResult<Boolean> removeItemCommon(Long memberId,
			Long cartId, Integer status) {

		PersonalCarts personalCarts = new PersonalCarts();

		personalCarts.setMemberId(memberId);

		personalCarts.setCartId(cartId);

		personalCarts.setState(CartsConstant.CartsStatusConstant.ON_SALE);

		List<PersonalCarts> personalCartsList = personalCartManager
				.find(personalCarts);

		if (personalCartsList == null || personalCartsList.size() == 0) {

			log.error("删除失败，原因cartsId:" + personalCarts.getCartId()
					+ " 不属于该买家:" + personalCarts.getMemberId());

			return ApiResult.newErrorResult(
					CartsErrorEnum.DELETE_ERROR.getErrorCode(),
					CartsErrorEnum.DELETE_ERROR.getErrorMessage());
		}

		// 执行删除操作
		personalCarts.setTimeEdit(new Date());

		personalCarts.setState(status);

		int num = personalCartManager.update(personalCarts);

		return ApiResult.newSuccessResult(true);

	}

	private String convertSkuName(ItemSkuDO itemSku) {

		String SPACE = " ";

		String SPLIT = ",";

		StringBuffer output = new StringBuffer();

		if (itemSku == null || itemSku.getPropertyValueIdArr() == null) {

			return "";
		}

		String skus = itemSku.getPropertyValueIdArr();

		String[] ss = skus.split(SPLIT);

		for (String s : ss) {

			Long skuId = Long.valueOf(s);

			PropertyValueDO pv = itemSku.getPropertyValueDOMap().get(skuId);

			output.append(pv.getValue()).append(SPACE);

		}

		if (StringUtils.isEmpty(output)) {

			return "";
		}

		return output.substring(0, output.length() - 1);
	}
}
